package cn.codergege.demo.config

import com.alibaba.druid.pool.DruidDataSource
import com.alibaba.druid.support.http.StatViewServlet
import com.alibaba.druid.support.http.WebStatFilter
import org.springframework.boot.context.properties.ConfigurationProperties
import org.springframework.boot.web.servlet.FilterRegistrationBean
import org.springframework.boot.web.servlet.ServletRegistrationBean
import org.springframework.context.annotation.Bean
import org.springframework.context.annotation.Configuration
import org.springframework.context.annotation.Profile
import java.util.*
import javax.sql.DataSource

@Configuration
@Profile("dev", "prod")
class DruidDataSourceConfig {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    fun druidDataSource(): DataSource {
        return DruidDataSource()
    }

    // 配置 druid 监控
    // 1. 后台 servlet
    @Bean
    fun statViewServlet(): ServletRegistrationBean<StatViewServlet> {
        val bean = ServletRegistrationBean(StatViewServlet(), "/druid/*")

        val initParams = HashMap<String, String>()
        initParams["loginUsername"] = "admin"
        initParams["loginPassword"] = "111111"
        initParams["allow"] = ""//默认就是允许所有访问
//        initParams["deny"]
        bean.initParameters = initParams

        return bean
    }

    // 2. 用于监控的 filter
    @Bean
    fun webStatFilter(): FilterRegistrationBean<WebStatFilter> {
        val bean = FilterRegistrationBean<WebStatFilter>()
        bean.setFilter(WebStatFilter())

        val initParams = HashMap<String, String>()
        initParams["exclusions"] = "*.js,*.css,/druid/*"
        bean.initParameters = initParams
        bean.urlPatterns = Arrays.asList("/*")

        return bean
    }
}
